package com.yonyou.crm.base.brand.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.base.brand.entity.BrandVO;
import com.yonyou.crm.bpub.refervalue.entity.ReferDataVO;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.enumeration.service.EnumBizServiceImpl;
import com.yonyou.crm.common.exception.CrmBusinessException;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.EnumFieldRelation;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.field.relation.RefFieldRelation;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.sys.org.service.SysOrgBizServiceImpl;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class BrandsBizServiceImpl extends BaseBizServiceImpl<BrandVO> {

	@Autowired
	private SysOrgBizServiceImpl orgService;
	@Autowired
	private EnumBizServiceImpl enumService;

	public List<BrandVO> getList() {
		List<Map<String, Object>> brandList = dao.selectList(BrandVO.class, "getList");
		List<BrandVO> returnBrandList = new ArrayList<BrandVO>();
		if (brandList != null && brandList.size() > 0) {
			for (int i = 0; i < brandList.size(); i++) {
				BrandVO brandVO = (BrandVO) brandList.get(i);
				returnBrandList.add(brandVO);
			}
		}
		trans(returnBrandList);
		return returnBrandList;
	}

	private List<BrandVO> trans(List<BrandVO> brandList) {

		if (brandList != null && brandList.size() > 0) {

			List<FieldRelation<BrandVO>> relations = new ArrayList<FieldRelation<BrandVO>>();
			relations.add(new RefFieldRelation<BrandVO>(BrandVO.class, "orgId", new String[] { "orgName" }, orgService,
					"selectFieldsByIds"));
			relations.add(new EnumFieldRelation<BrandVO>(BrandVO.class, "enableState", "enableStateName", enumService,
					"enable_state"));

			new FieldRelationHandler<BrandVO>().handler(brandList, relations);
		}

		return brandList;
	}

	public BrandVO getDetail(Long id) {
		BrandVO brandVO = super.getVOById(BrandVO.class, id);
		trans(Arrays.asList(brandVO));
		return brandVO;
	}

	@Override
	protected void beforeSaveVO(BrandVO vo) {

		if (getCountByName(null, vo.getName()) > 0) {
			throw new CrmBusinessException("品牌名称重复，保存失败！");
		}
		
		super.beforeSaveVO(vo);
	}
	
	@Override
	protected void afterSaveVO(BrandVO vo) { 
		super.afterSaveVO(vo);
		trans(Arrays.asList(vo));
	}

	public int getCountByName(Long id, String name) {
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("id", id);
		paraMap.put("name", name);
		paraMap.put("tenantId", InvocationInfoProxy.getTenantid());
		return dao.countAll(BrandVO.class, "getCountByName", paraMap);
	}

	public BrandVO insert(BrandVO brand) {
		return super.saveVO(brand);
	}

	@Override
	protected void beforeUpdateVO(BrandVO vo) {
		
		if (getCountByName(vo.getId(), vo.getName()) > 0) {
			throw new CrmBusinessException("品牌名称重复，保存失败！");
		}
		
		super.beforeUpdateVO(vo);
	}
	
	@Override
	protected void afterUpdateVO(BrandVO vo) {
		super.afterUpdateVO(vo);
		trans(Arrays.asList(vo));
	}

	public BrandVO update(BrandVO brand) {
		return super.updateVO(brand);
	}

	@Override
	protected void beforeDeleteVO(BrandVO vo) {
		Date date = new Date();
		Long loginUserID = new Long(InvocationInfoProxy.getParameter("id"));
		vo.setDeletedTime(date);
		vo.setDeletedUserId(loginUserID);
	}

	public int delete(Long id) {
		BrandVO brandVO = new BrandVO();
		brandVO.setId(id);
		return super.deleteVO(brandVO);
	}

	public String batchDelete(String[] ids) {
		
		if (ids == null || ids.length == 0) {
			return "";
		}

		Set<String> idSet = new HashSet<String>();
		for (String id : ids) {
			idSet.add(id);
		}
		
		int totalCount = idSet.size();
		
		StringBuffer reasonBuffer = new StringBuffer("【");

		//是否被产品引用
		List<Map<String, Object>> brandList = getProductByBrand(idSet.toArray(new String[0]));
		
		if (brandList != null && brandList.size() > 0) {
			
			for (Map<String, Object> map : brandList) {
				
				reasonBuffer.append(map.get("name"));
				reasonBuffer.append(",");

				String typeId = map.get("id").toString();
				//被产品引用品牌不能删除
				idSet.remove(typeId);
			}
			reasonBuffer.delete(reasonBuffer.length()-1, reasonBuffer.length());
			reasonBuffer.append("】已被产品引用，当前品牌不可删除！");
		}
		
		int successCount = idSet.size();
		int failCount = totalCount - idSet.size();
		String message = failCount == 0 ? "成功" + successCount + "条。" : "成功" + successCount + "条，失败" + failCount + "条。\n失败原因：" + reasonBuffer.toString();
		
		if (successCount > 0) {
			super.batchDeleteByIDs(BrandVO.class, idSet);
		}
		
		return message;
	}

	public BrandVO updateEnableState(Long id, Integer enableState) {
		Byte enableStateByte = (byte) enableState.intValue();
		BrandVO brandVO = new BrandVO();
		brandVO.setId(id);
		brandVO.setEnableState(enableStateByte);
		brandVO.setEnableTime(new Date());
		brandVO.setEnableUserId(new Long(InvocationInfoProxy.getParameter("id")));
		return super.updateVO(brandVO);
	}

	public void batchUpdateEnableState(String[] idArray, Integer enableState) {
		Byte en = (byte) enableState.intValue();
		Map<String, Object> enableParaMap = new HashMap<String, Object>();
		enableParaMap.put("ids", idArray);
		enableParaMap.put("enableState", en);
		enableParaMap.put("enableUserId", new Long(InvocationInfoProxy.getParameter("id")));
		enableParaMap.put("enableTime", new Date());
		dao.updateSql(BrandVO.class, "batchUpdateEnableState", enableParaMap);
	}
	
	/*
	 * 获取参照档案列表
	 */
	public List<ReferDataVO> getRefervalues(Page<BrandVO> page, Map<String, Object> paraMap) {
		// TODO 加权限
		Page<BrandVO> pageVO = dao.pageSelect(BrandVO.class, page, "selectRefervalues", "countRefervalues", paraMap);
		List<BrandVO> voList = pageVO.getData();
		
		List<ReferDataVO> rsList = new ArrayList<ReferDataVO>();
		for (BrandVO vo : voList) {
			ReferDataVO referDataVO = new ReferDataVO();
			referDataVO.setId(vo.getId().toString());
			referDataVO.setValue(vo.getName());
			
			rsList.add(referDataVO);
		}
		return rsList;
	}
	
	/*
	 * 获取参照档案列表
	 */
	public List<BrandVO> getRefervaluesForApp(Page<BrandVO> page, Map<String, Object> paraMap) {
		// TODO 加权限
		Page<BrandVO> pageVO = dao.pageSelect(BrandVO.class, page, "selectRefervalues", "countRefervalues", paraMap);
		List<BrandVO> voList = pageVO.getData();
		return voList;
	}
	
	/*
	 * 获取参照档案列表(不分页)
	 */
	public List<ReferDataVO> getNoPageRefervalues(Map<String, Object> paraMap) {
		// TODO 加权限
		List<BrandVO> voList = dao.selectVoList(BrandVO.class, "NoPageRefervalues", paraMap);
		
		List<ReferDataVO> rsList = new ArrayList<ReferDataVO>();
		for (BrandVO vo : voList) {
			ReferDataVO referDataVO = new ReferDataVO();
			referDataVO.setId(vo.getId().toString());
			referDataVO.setValue(vo.getName());
			
			rsList.add(referDataVO);
		}
		return rsList;
	}

	public Page<BrandVO> getPageList(Page<BrandVO> page, Map<String, Object> paramMap) {
		Page<BrandVO> brandPage = null;
		if (paramMap != null) {
			brandPage = super.pageSelect(BrandVO.class, page, paramMap.keySet().toArray(new String[0]), paramMap.values().toArray(new Object[0]));
		}
		else {
			brandPage = super.pageSelect(BrandVO.class, page, null, null);
		}

		trans(brandPage.getData());

		return brandPage;
	}
	
	/**
	 * 参照列表
	 * 参照字段：id、名称、英文名称、备注
	 * @param paraMap
	 * @return
	 */
	public List<BrandVO> getRefList(Map<String, Object> paraMap) {

		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}
		
		paraMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		
		return dao.selectVoList(BrandVO.class, "getRefList", paraMap);
	}
	
	/**
	 * 分页参照列表
	 * 参照字段：id、名称、英文名称、备注
	 * @param page
	 * @param paraMap
	 * @return
	 */
	public Page<BrandVO> getRefPage(Page<BrandVO> page, Map<String, Object> paraMap) {

		if (paraMap == null) {
			paraMap = new HashMap<String, Object>();
		}
		
		paraMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
		
		return dao.pageSelect(BrandVO.class, page, "getRefPage", "countRefPage", paraMap);
	}
	
	/**
	 * 品牌名称翻译
	 * @param ids
	 * @return
	 */
	public Object selectFieldsByIds(Object[] ids) {
		Map<String, Object> para = new HashMap<String, Object>();
		para.put("ids", ids);
		return dao.selectList(BrandVO.class, "selectFieldsByIds", para);
	}
	
	/**
	 * 校验品牌是否被产品引用
	 * @param brandIds
	 * @return
	 */
	public List<Map<String, Object>> getProductByBrand(String[] brandIds) {
		if (brandIds == null || brandIds.length == 0) {
			return null;
		}
		return dao.selectList(BrandVO.class, "getProductByBrand", brandIds);
	}
}
